package com.webserver.http;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**
 * @author liyang
 * @version 1.0
 * @package com.webserver.http
 * @file HttpServletResponse.java
 * @description
 * @time 2024-05-15 15:23
 */
public class HttpServletResponse {
    private Socket socket;
    private int statusCode = 200;
    private String statusReason = "OK";
    //响应头暂是固定为那两行，留白

    //响应正文
    private File contentFile;

//    此时发送工作不在构造方法中干（与请求的方法不同）
    public HttpServletResponse(Socket socket){
        this.socket = socket;
    }

//    在这干：以Http相应格式发送给浏览器
    public void response() throws IOException {
        sendStatusLine();
        sendHeaders();
        sendContent();
    }

    private void sendStatusLine() throws IOException {
        println("HTTP/1.1" + " " + statusCode + " " + statusReason);
    }
    private void sendHeaders() throws IOException {
        println("Content-Type: text/html");
        println("Content-Length: "+contentFile.length());
        println("");
    }
    private void sendContent() throws IOException {
        OutputStream out = socket.getOutputStream();
        FileInputStream fis = new FileInputStream(contentFile);

        int len;//每次读取的字节量
        byte[] buf = new byte[1024*10];//10kb
        while((len = fis.read(buf))!=-1){
//                fos.write(buf,0,len);
//                把buf数组的第0 到 第len个字节都写给浏览器
            out.write(buf,0,len);
        }
    }

    private void println(String line) throws IOException {
        OutputStream out = socket.getOutputStream();
        //http要求文本部分（行，头）为纯文本，也就是ISO_8859_1字符集
        byte[] data = line.getBytes(StandardCharsets.ISO_8859_1);
        out.write(data);
        out.write(13);//发送回车符
        out.write(10);//发送换行符
    }

    //自动生成对应的get,set方法（与请求时只get看不同）
    public int getStatusCode() {
        return statusCode;
    }

    public void setStatusCode(int statusCode) {
        this.statusCode = statusCode;
    }

    public String getStatusReason() {
        return statusReason;
    }

    public void setStatusReason(String statusReason) {
        this.statusReason = statusReason;
    }

    public File getContentFile() {
        return contentFile;
    }

    public void setContentFile(File contentFile) {
        this.contentFile = contentFile;
    }
}
